<template>
  <div class="footprints-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的收藏与推荐</span>
        </div>
      </template>
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="我的收藏" name="footprints">
          <el-table :data="footprints" style="width: 100%" v-loading="loading">
            <el-table-column prop="property.name" label="收藏内容" width="200" />
            <el-table-column prop="notes" label="我的评价">
              <template #default="scope">
                <span>{{ scope.row.notes || '暂无评价' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="我的打分" width="200">
              <template #default="scope">
                <el-rate
                    v-model="scope.row.rating"
                    :max="5"
                    @change="(newRating) => handleRatingChange(scope.row, newRating)"
                />
              </template>
            </el-table-column>
            <el-table-column label="收藏时间" width="200">
              <template #default="scope">
                <span>{{ new Date(scope.row.added_at).toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑评价</el-button>
                <el-popconfirm
                    title="确定要取消收藏吗？"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    @confirm="handleDelete(scope.row)"
                >
                  <template #reference>
                    <el-button size="small" type="danger">取消收藏</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="个性化推荐" name="recommendations">
          <Recommendation />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog v-model="dialogVisible" title="编辑评价" width="30%">
      <el-form :model="currentFootprint">
        <el-form-item label="评价内容">
          <el-input
              v-model="currentFootprint.notes"
              :rows="4"
              type="textarea"
              placeholder="请输入你的评价"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNotes">保存</el-button>
        </span>
      </template>
    </el-dialog>

      <div class="fab-button">
        <el-tooltip content="返回个人中心" placement="left">
          <el-button type="primary" circle :icon="Back" @click="handleExit" />
        </el-tooltip>
      </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { footprintApi } from '@/api/footprints.js';
import { ElMessage } from 'element-plus';
import Recommendation from './Recommendation.vue';
import {Back} from "@element-plus/icons-vue"; // 导入推荐组件

const router = useRouter();
const footprints = ref([]);
const loading = ref(true);
const dialogVisible = ref(false);
const currentFootprint = ref({ property: {}, notes: '', rating: 0 });
const activeTab = ref('footprints'); // 默认显示“我的收藏”标签页

onMounted(() => {
  fetchFootprints();
});

const fetchFootprints = async () => {
  loading.value = true;
  try {
    const res = await footprintApi.getFootprints();
    console.log('API Response:', res);
    if (res.data && Array.isArray(res.data.data.list)) {
      footprints.value = res.data.data.list.filter(fp => fp.property);
    } else {
      footprints.value = [];
      console.error('API response format is not as expected:', res.data);
      ElMessage.error('获取足迹列表失败：数据格式错误');
    }
  } catch (error) {
    ElMessage.error('足迹列表加载失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const handleRatingChange = async (row, newRating) => {
  try {
    await footprintApi.updateFootprint(row.property.id, { rating: newRating });
    ElMessage.success('评分更新成功');
    const index = footprints.value.findIndex(fp => fp.property.id === row.property.id);
    if (index !== -1) {
      footprints.value[index].rating = newRating;
    }
  } catch (error) {
    ElMessage.error('评分更新失败');
    row.rating = footprints.value.find(fp => fp.property.id === row.property.id)?.rating || row.rating;
    console.error(error);
  }
};

const handleEdit = (row) => {
  currentFootprint.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

const saveNotes = async () => {
  if (!currentFootprint.value || !currentFootprint.value.property) return;
  try {
    await footprintApi.updateFootprint(currentFootprint.value.property.id, { notes: currentFootprint.value.notes });
    ElMessage.success('评价更新成功');
    dialogVisible.value = false;
    const index = footprints.value.findIndex(fp => fp.property.id === currentFootprint.value.property.id);
    if (index !== -1) {
      footprints.value[index].notes = currentFootprint.value.notes;
    }
  } catch (error) {
    ElMessage.error('评价更新失败');
    console.error(error);
  }
};

const handleDelete = async (row) => {
  try {
    await footprintApi.deleteFootprint(row.property.id);
    ElMessage.success('已取消收藏');
    footprints.value = footprints.value.filter(fp => fp.property.id !== row.property.id);
  } catch (error) {
    ElMessage.error('操作失败');
    console.error(error);
  }
};

const handleExit = async () => {
  await router.push('/profile');
};

const handleTabClick = () => {
  // 可选：切换标签时触发特定逻辑，例如刷新推荐
  if (activeTab.value === 'recommendations') {
    console.log('切换到个性化推荐标签');
  }
};
</script>

<style scoped>
.footprints-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fab-button {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 100;
}
</style>
